package filters.push;

import helper.PlanarImageWrapper;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;

import presentation.ImageFrame;
import at.fhv.framework.filter.PassivePushFilter;

import com.sun.media.jai.widget.DisplayJAI;

/**
 * The SinkFilter class.
 * 
 * @author Michael Sieber
 */
public class SinkPushFilter extends
		PassivePushFilter<PlanarImageWrapper, PlanarImageWrapper> {
	private static Logger LOGGER = Logger.getLogger(SinkPushFilter.class);
	private final String SAVE = "src.resources/filtered.jpg";
	private ImageFrame _frame;

	/**
	 * 
	 * @param source
	 */
	public SinkPushFilter(ImageFrame frame) {
		super(null);
		_frame = frame;
	}

	/*
	 * {@inheritDoc}
	 */
	@Override
	protected boolean execute(PlanarImageWrapper entity, PlanarImageWrapper data) {
		entity.setImage(data.getImage());

		// save
		BufferedImage bi = entity.getImage().getAsBufferedImage();
		File outputfile = new File(SAVE);
		try {
			ImageIO.write(bi, "png", outputfile);
			LOGGER.info("Image saved at location: " + SAVE);
		} catch (IOException e) {
			LOGGER.info("Unable to save image.", e);
		}
		return true;
	}

	/*
	 * {@inheritDoc}
	 */
	@Override
	protected PlanarImageWrapper createEntity() {
		return new PlanarImageWrapper();
	}

	@Override
	public void write(PlanarImageWrapper data)
	{
		_frame.setModifiedImageAfterPush(new DisplayJAI(data.getImage()));
	}
}
